import path from 'path'
import { app, BrowserWindow, ipcMain, Menu } from 'electron'
import lodashGet from 'lodash/get'
import services from './service'

process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'

function createMainWindow() {
    Menu.setApplicationMenu(null)
    const win = new BrowserWindow({
        width: 1200,
        height: 800,
        show: false,
        webPreferences: {
            preload: path.join(__dirname, '../preload/index.js'),
        },
    })

    if (!app.isPackaged) {
        win.loadURL('http://localhost:5174')
        win.webContents.openDevTools()
    } else {
        win.loadFile(path.join(__dirname, '../renderer/index.html'))
    }
}

function initBridge() {
    ipcMain.handle('jsBridge', async (event, paths: string[], ...args: any[]) => {
        const service = lodashGet(services, paths)
        if (service && typeof service === 'function') {
            return service(...args, event)
        } else {
            throw new Error(`Service not found: ${paths.join('.')}`)
        }
    })
}

function bootstrap() {
    initBridge()
    app.on('ready', () => {
        createMainWindow()
    })
}

bootstrap()